package cn.flying.cloud.flow.core.servicetask;

import javax.annotation.Resource;

import java.util.Map;
import java.util.Optional;

import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 流程完结闭环处理
 *
 * @author: admin
 * @date: 2025年07月16日 10:07
 * @version: 1.0
 */
@Component
public class CloseLoopHandling implements JavaDelegate {

    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private RuntimeService runtimeService;

    @Override
    public void execute(DelegateExecution delegateExecution) {
        String instanceId = delegateExecution.getProcessInstanceId();
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).singleResult();

        Map<String, AbstractCloseLoopHandle> beans = applicationContext.getBeansOfType(AbstractCloseLoopHandle.class);
        if (beans.isEmpty()) {
            return;
        }
        Optional<AbstractCloseLoopHandle> optional = beans.values().stream().filter(b -> instance.getProcessDefinitionKey().equals(b.key())).findAny();
        if (optional.isPresent()) {
            AbstractCloseLoopHandle handle = optional.get();
            handle.execute(delegateExecution);
        }
    }
}
